package com.example.demo5.config;

import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.simp.stomp.StompCommand;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.messaging.support.ChannelInterceptorAdapter;
import org.springframework.messaging.support.MessageHeaderAccessor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;

import javax.servlet.http.HttpSession;

/**
 * Created by Davis on 2017/8/4.
 */
public class WebsocketChannelInterceptor extends ChannelInterceptorAdapter {

    @Override
    public Message<?> preSend(Message<?> message, MessageChannel channel) {

        StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class);
        HttpSession session = (HttpSession)accessor.getSessionAttributes().get("HTTP_SESSION");
        if (StompCommand.CONNECT.equals(accessor.getCommand())) {
//            SecurityContextImpl springSecurityContext = (SecurityContextImpl)session.getAttribute("SPRING_SECURITY_CONTEXT");
//            Authentication authentication = springSecurityContext.getAuthentication();
//            BasicUser user = ((BasicAuthenticationProvider.BasicUserDetails) authentication.getPrincipal()).getUserDetail();
//            if(user == null || ! userValid(user)){
//                System.out.println("不允许该用户 websocket 连接");
//
//            }
        }
        return super.preSend(message, channel);
    }

    @Override
    public void postSend(Message<?> message, MessageChannel channel, boolean sent) {
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(message);
    }

}
